<!--
- Author:   .
- Date:    2017/7/4 0004.
- File:    index.
-->
<template>
  <div>
    <!--<app-down></app-down>-->
    <div class="Web_Box" :class="{'no-margin-bottom':editing}">
      <!--店铺商品Start-->
      <div class="gd lt0 wauto z99" v-show="memberInfo.is_brush_man == '1'">
        <div class="Tabs2">
          <ul>
            <li :class="{'on': orderType == '1'}" style="width: 100%" @click="switchOrderType('1')">购物车</li>
            <!--<li :class="{'on': orderType == '4'}" style="width: 50%" @click="switchOrderType('4')">积分商品</li>-->
          </ul>
        </div>
      </div>
      <div class="ShoppingCartPage" :class="{'margin-top-40': memberInfo.is_brush_man == '1' && $config.debugerUser.indexOf(memberInfo.member_id) != -1}">
        <div class="ShopGoods EditPro hidden bor_b_dcdddd mb10" style="margin-top: 40px;">
          <div class="ProList">
            <ul>
              <li v-for="item in goodsList.data">
                <div class="Choice" @click="switchSelect(item)" v-show="!editing">
                  <i class="iconfont icon-pitch2" v-if="selectedCartIdList.indexOf(item.cart_id) === -1"></i>
                  <i class="iconfont icon-select" v-else></i>
                </div>
                <div class="Pic">
                  <img :src="$config.website + $config.goodsImgSrc + item.goods_image" alt=""/></div>
                <div class="Con" style="width: 10.5rem;">
                  <div class="pl20 f-cb">
                    <span class="detete" @click="delGoodsFromCart(item)"><i class="iconfont icon-del3" style="padding:0 5px"></i></span>
                    <h2 class="" style="width: 80%; margin: 0 !important;">
                      <span @click="gotoGoodsDetail(item.goods_commonid)">{{item.goods_name}}</span></h2>
                  </div>
                  <div class="cr_898989 pl20" v-show="(item.storage && item.storage <= 0) || item.goods_state != '1'">
                    <i class="iconfont icon-shixiao"></i>
                  </div>
                  <div class="pl20">
                    <p class="Attribute" v-show="item.goods_spec.length > 0">
                      <span v-for="attr in item.goods_spec">{{attr.name}} </span></p>
                    <div class="PriceQuantity f-cb" v-show="item.storage > 0">
                      <span class="fl cr_ea5413">￥{{item.goods_price | discount(item.groupbuy_rebate)}}</span>
                      <div class="Edit" v-show="item.goods_kind != '2'">
                        <i class="iconfont icon-jian1" :class="{'jian1-active': parseInt(item.goods_num) > parseInt(item.goods_add_num || 1)}" @click="reduceNum(item)"></i>
                        <input type="tel" class="num" @blur="handleNumChange(item)" v-model="item.goods_num" style="height: 1rem;border: none;display: inline-block;vertical-align: middle;width: 2.5rem;font-size: 0.8rem;color: #000;border-radius: 2px;text-align: center;">
                        <i class="iconfont icon-jia1" :class="{'jian1-active': parseInt(item.goods_num) + parseInt(item.goods_add_num || 1) < parseInt(item.storage)}" @click="addNum(item)" style="color: #898989"></i>
                      </div>
                    </div>
                  </div>
                </div>
              </li>
            </ul>
          </div>
        </div>
      </div>
      <!--店铺商品End-->
    </div>
    <div ref="cart-bottom" class="ShopGoodsOperation BottomGd" style="height: auto;" v-show="!editing">
      <div class="left fl">
        <i class="iconfont icon-select" @click="switchSelectAll(false)" v-if="selectedCartIdList.length > 0 && selectedCartIdList.length === goodsList.data.length"></i>
        <i class="iconfont icon-pitch2" @click="switchSelectAll(true)" v-else></i>
        <span class="text">全选</span>
        <div class="Statistics fr tr">
          <p class="Total">合计：<span class="cr_ea5413">￥{{totalPrice}}</span></p>
          <p class="Freight" style="background-color: transparent">不含运费</p>
        </div>
      </div>
      <div class="right fr">
        <button type="button" class="but" :class="{'confirm-unactive': totalNum <= 0}" @click="gotoOrderConfirm">结算({{totalNum}})</button>
      </div>
    </div>
    <!--<empty-data :show="goodsList.requested && goodsList.data.length <= 0"></empty-data>-->
    <div class="Cart_nodata" v-show="goodsList.requested && goodsList.data.length <= 0">
      <i class="iconfont icon-kong"></i>
      <p>购物车还是空的哦</p>
      <a href="javascript:void(0)" @click="gotoShoping">去逛逛</a>
    </div>
    <back-nav></back-nav>
  </div>
</template>

<script>
  import {MessageBox} from 'mint-ui'
  import {mapModules, mapRules} from 'vuet'

  export default {
    mixins: [
      mapModules({memberInfo: 'memberInfo'}),
      mapRules({need: ['memberInfo']})
    ],
    data() {
      return {
        orderType: this.$route.query.orderType || '1',
        goodsList: {requested: false, data: []},
        editing: false, // 是否正在编辑
        selectedCartIdList: []
      }
    },
    computed: {
      totalPrice: function () {
        let total = 0
        for (let i = 0; i < this.selectedCartIdList.length; i++) {
          for (let j = 0; j < this.goodsList.data.length; j++) {
            if (this.goodsList.data[j].cart_id === this.selectedCartIdList[i]) {
              if (!this.goodsList.data[j].goods_num || this.goodsList.data[j].goods_num == '') {
                total += 0
              } else {
                total += parseFloat(this.goodsList.data[j].goods_price) * parseFloat(this.goodsList.data[j].groupbuy_rebate / 100) * parseInt(this.goodsList.data[j].goods_num)
              }
              continue
            }
          }
        }
        return total.toFixed(2)
      },
      totalNum: function () {
        let total = 0
        for (let i = 0; i < this.selectedCartIdList.length; i++) {
          for (let j = 0; j < this.goodsList.data.length; j++) {
            if (this.goodsList.data[j].cart_id === this.selectedCartIdList[i]) {
              total += parseInt(this.goodsList.data[j].goods_num)
              continue
            }
          }
        }
        return total
      }
    },
    components: {},
    created() {
      this.getGoodsListInCart()
    },
    mounted() {
      if (this.$utils.isIphoneX()) {
        this.$refs['cart-bottom'].style.paddingBottom = '34px'
      }
    },
    methods: {
      switchOrderType(value) {
        this.orderType = value
        this.goodsList = {requested: false, data: []}
        this.getGoodsListInCart()
      },
      gotoShoping() {
        if (this.orderType == '1') {
          this.$router.push({name: 'home'})
        } else if (this.orderType == '4') {
          this.$router.push({name: 'hong-index'})
        }
      },
      gotoGoodsDetail(goodsCommonid) {
        this.$router.push({name: 'goods-detail', params: {id: goodsCommonid}})
      },
      gotoOrderConfirm() {
        if (this.selectedCartIdList.length <= 0) {
          this.$toast('请先选择要结算的商品')
          return
        }
        let goods_kind = ''
        for (let i = 0; i < this.selectedCartIdList.length; i++) {
          for (let j = 0; j < this.goodsList.data.length; j++) {
            if (this.goodsList.data[j].cart_id === this.selectedCartIdList[i]) {
              if (goods_kind == '') {
                goods_kind = this.goodsList.data[j].goods_kind
              } else if (goods_kind != '' && goods_kind != this.goodsList.data[j].goods_kind) {
                this.$toast('VIP会员专享体验商品不能和其他商品一起结算，请分开结算。')
                return
              }
            }
          }
        }
        let cartIdListStr = this.selectedCartIdList.join(',')
        this.$router.push({name: 'order-confirm', query: {cart: cartIdListStr, orderType: this.orderType}})
      },
      switchEditing(boolValue) {
        this.editing = boolValue
      },
      findGoodsInGoodsList(cartId) {
        for (let i = 0; i < this.goodsList.data.length; i++) {
          if (this.goodsList.data[i].cart_id === cartId) {
            return {goods: this.goodsList.data[i], index: i}
          }
        }
        return {goods: null, index: -1}
      },
      switchSelect(goods) {
        let index = this.selectedCartIdList.indexOf(goods.cart_id)
        if (index !== -1) { // 已选
          this.selectedCartIdList.splice(index, 1)
        } else { // 未选
          this.selectedCartIdList.push(goods.cart_id)
        }
      },
      switchSelectAll(boolValue) {
        if (!boolValue) { // 全不选
          this.selectedCartIdList = []
        } else { // 全选
          let tmpArray = []
          for (let i = 0; i < this.goodsList.data.length; i++) {
            tmpArray.push(this.goodsList.data[i].cart_id)
          }
          this.selectedCartIdList = tmpArray
        }
      },
      handleNumChange(goods) {
        let packNum = parseInt(goods.goods_add_num || 1)
        console.log('blur..')
        if (goods.goods_num == '' || goods.goods_num == 0) {
          goods.goods_num = packNum
          return
        }
        let mul = parseInt(parseInt(goods.goods_num) / packNum) // 倍数
        let remain = parseInt(goods.goods_num) % packNum // 余数
        if (remain != 0) {
          goods.goods_num = packNum * (mul + 1)
        }
        if (parseInt(goods.goods_num) + packNum >= parseInt(goods.storage)) {
          this.$toast('超过商品库存数量了~')
          return
        }
        this.$request.modifyGoodsNumToBuy(goods.cart_id, parseInt(goods.goods_num)).then(() => {
        }).catch(e => {
          this.$toast('修改购买数量失败:' + e.msg)
        })
      },
      addNum(goods) {
        let packNum = parseInt(goods.goods_add_num || 1)
        if (!goods.storage) {
          this.$toast('尚未获取到该商品的库存')
          return
        }
        if (parseInt(goods.goods_num) + packNum >= parseInt(goods.storage)) {
          this.$toast('超过商品库存数量了~')
          return
        }
        this.$request.modifyGoodsNumToBuy(goods.cart_id, parseInt(goods.goods_num) + packNum).then(() => {
          let goodsEdit = this.findGoodsInGoodsList(goods.cart_id).goods
          goodsEdit.goods_num = parseInt(goodsEdit.goods_num)
          goodsEdit.goods_num += packNum
        }).catch(e => {
          this.$toast('修改购买数量失败:' + e.msg)
        })
      },
      reduceNum(goods) {
        let packNum = parseInt(goods.goods_add_num || 1)
        if (parseInt(goods.goods_num) <= packNum) {
          return
        }
        this.$request.modifyGoodsNumToBuy(goods.cart_id, goods.goods_num - packNum).then(() => {
          let goodsEdit = this.findGoodsInGoodsList(goods.cart_id).goods
          goodsEdit.goods_num = parseInt(goodsEdit.goods_num)
          goodsEdit.goods_num -= packNum
        }).catch(e => {
          this.$toast('修改购买数量失败' + e.msg)
        })
      },
      getGoodsListInCart() {
        this.$request.getGoodsListInCart(this.orderType).then(data => {
          this.goodsList.data = data
        }).catch(e => {
          console.error(e)
          this.$toast('获取购物车列表失败:' + e.msg)
        }).finally(() => {
          this.goodsList.requested = true
        })
      },
      delGoodsFromCart(goods) {
        MessageBox.confirm(`你确定要删除该商品吗?`).then(action => {
          this.$request.delGoodsFromCart(goods.cart_id).then(data => {
            let index = this.findGoodsInGoodsList(goods.cart_id).index
            this.goodsList.data.splice(index, 1)
            let index2 = this.selectedCartIdList.indexOf(goods.cart_id)
            if (index2 != -1) {
              this.selectedCartIdList.splice(index2, 1)
            }
            this.$toast('删除成功')
          }).catch(e => {
            this.$toast('删除购物车失败:' + e.msg)
          })
        }).catch(() => {
        })
      }
    }
  }
</script>

<style>
  .margin-top-40 {
    margin-top: 40px;
  }

  .no-margin-bottom {
    margin-bottom: 0;
  }

  .jian1-active {
    color: #f83166 !important;
  }

  .confirm-unactive {
    background-color: #dddddd !important;
  }
</style>
